import React, {Component} from "react";

export default function withData(WrappedComponent, data) {
  return class extends Component {
    constructor (props) {
      super(props)
      this.state = {
        height: 0,
        fall: false,
        ...data,
      }
      // 生长间隔时间
      this.growTimes = props.growTimes ? props.growTimes : 100
      this.maxHeight = props.maxHeight
    }
    intervalTimer = null
    timeoutTimer = null
    componentDidMount () {
      this.intervalTimer = setInterval(this.leafGrow, this.growTimes / (this.props.speed ?? 1))
    }
    componentWillUnmount () {
      clearInterval(this.intervalTimer)
      clearTimeout(this.timeoutTimer)
    }
    // 树叶生长
    leafGrow = () => {
      // 落叶时停止生长
      if (this.state.fall) return
      if (this.state.height < this.maxHeight) {
        this.setState({height: this.state.height+.1})
      } else {
        clearInterval(this.intervalTimer)
        this.timeoutTimer = setTimeout(this.leafFall, 3000 / (this.props.speed ?? 1))
      }
    }
    leafFall = () => {
      this.setState({fall: true})
      // 重新生长
      this.timeoutTimer = setTimeout(this.reset, 5000 / (this.props.speed ?? 1))
    }
    reset = () => {
      this.setState({height: 0, fall: false})
      this.intervalTimer = setInterval(this.leafGrow, this.growTimes / (this.props.speed ?? 1))
    }
    render() {
      const newProps = Object.assign({}, this.props, {
        height: this.state.height,
        fall: this.state.fall,
        growTimes: this.growTimes,
      })
      return <WrappedComponent {...newProps}></WrappedComponent>
    }
  }
}